import { computed, unref, useSlots } from 'vue'
import type { Ref } from 'vue'

export function useColumnList(colList: any, maxDeep: number, isXScroll: boolean, fixedWidthDefault: Ref ) {
  const slots = useSlots()
  // 获取title 插槽
  function getHeaderSlots(arr: any) {
    return arr.filter((item: any) => item.slotHeader && slots[item.slotHeader])
  }

  // 获取列宽和
  function getColWidth(arr: any, defaultWidth: number): number {
    return +arr
      .reduce((pre: any, cur: any) => {
        pre += cur.width ? +cur.width : defaultWidth
        return pre
      }, 0)
      .toFixed(2)
  }

  // 表头数据
  function getColumnArr(list: any, maxDeep: number) {
    return list.reduce(
      (pre: any, cur: any) => {
        pre[cur.deep - 1].push(cur)
        return pre
      },
      Array.from({ length: maxDeep }).map(() => [])
    )
  }
  // 列list
  const fixedArr = ['left', 'center', 'right']
  const columnArr = computed(() => {

    let obj = fixedArr.reduce((pre: any, key) => {
      pre[key] = []
      return pre
    }, {})

    colList.forEach((item: any) => {
      // fixed 值为 String
      if (item.fixed === 'left' || item.fixed === 'right') {
        obj[item.fixed].push(item)
      } else {
        obj.center.push(item)
      }
    })

    const wt = fixedArr.reduce((pre: any, key) => {
      pre[key] = getColWidth(obj[key], fixedWidthDefault.value)
      return pre
    }, {})

    const arr: any = []
    Object.keys(obj).forEach(key => {
      if (obj[key].length > 0) {
        arr.push({
          titleList: getColumnArr(obj[key], maxDeep),
          col: obj[key].filter((item: any) => !item.hasChildren),
          fixed: key,
          colWidth: wt[key], // 列宽度
          // 此处宽度需动态计算,屏幕宽度不一样对应的1rem等于多少px不一样
          width: ['left', 'right'].includes(key) ? wt[key] + 'px' : `calc(100% - ${wt.left + wt.right}px)`,
          headerSlots: getHeaderSlots(obj[key]),
          colSlots: obj[key].filter((item: any) => slots[item.key]),
          shadow: key !== 'center' ? isXScroll : false
        })
      }
    })
    // 最后一列添加类名
    const objeFirst = arr[0]
    objeFirst.isFirstCol = true
    const objeEnd = arr[arr.length - 1]
    objeEnd.isLastCol = true
    return arr
  })

  console.log('columnArr===>', unref(columnArr))
  return { columnArr: unref(columnArr) }
}
